import "./my-work.less";
import workIcon from "@/assets/images/work_icon.png";
import { Checkbox } from "antd";
import AddIcon from "@/assets/images/add_work_menu_icon.png";
import moreWhite from "@/assets/images/more_white.png";
import Work_1 from "@/assets/images/work_1.png";
import Work_2 from "@/assets/images/work_2.png";
import Work_3 from "@/assets/images/work_3.png";
import Work_4 from "@/assets/images/work_4.png";
import Work_5 from "@/assets/images/work_5.png";
import Work_6 from "@/assets/images/work_6.png";
import Work_7 from "@/assets/images/work_7.png";
import Work_8 from "@/assets/images/work_8.png";
import Work_9 from "@/assets/images/work_9.png";
import Work_10 from "@/assets/images/work_10.png";
import Work_11 from "@/assets/images/work_11.png";

import Work_8_a from "@/assets/images/work_8_a.png";
import Work_6_a from "@/assets/images/work_6_a.png";
import Work_9_a from "@/assets/images/work_9_a.png";

import React, { useState, useEffect, useCallback } from "react";
import {
  getMyWorkMenu,
  myworkInfolistMenu,
  deleteMyworkMenu,
  saveMenu,
  myworkInfoSaveMenu,
  deleteMenu,
  updateMyworkMenu,
  deleteFinishedMyworkMenu
} from "@/api/modules/my-work";
//

import { message } from "@/hooks/useMessage";

const MyWork: React.FC<React.HTMLProps<Element>> = props => {
  // 存储点击ID
  const [getMenus, setgetMenus] = useState<any>(undefined);
  // 首页获取渲染数据
  const [getList, setgetList] = useState<any[]>([]); // 是否显示更多的弹框
  // props.type init 为图标 list为列表
  const [isShowModal, setisShowModal] = useState(false); // 是否显示更多的弹框
  const [isShowDelAllCheck, setisShowDelAllCheck] = useState(false); // 是否显示更多弹窗中点击三个点后显示删除全部已读
  const [leftMenuData, setleftMenuData] = useState([] as any); // 更多-左侧菜单树数组
  const [rightChildArr, setrightChildArr] = useState([] as any); // 右侧子菜单
  const [rightChildAddValue, setrightChildAddValue] = useState(""); // 子菜单新增input值
  // 更多弹窗点解三个点切换删除全部已读显示状态
  const modal_more_click = () => {
    setisShowDelAllCheck(!isShowDelAllCheck);
  };
  let leftMenuClickTimeOut: any;
  //添加左侧树
  const addLeftMenuClick = () => {
    if (!leftMenuData[leftMenuData.length - 1]["menuId"]) {
      return;
    }
    const pushData = { ...leftMenuData[0] };
    // 重置一下数据
    pushData["infoCount"] = 0;
    pushData["menuName"] = null;
    pushData["menuId"] = null;
    pushData["isAct"] = false;
    pushData["iptVal"] = "";
    pushData["isEdit"] = true;
    leftMenuData.push(pushData);
    console.log("左侧菜单添加数据---", pushData);
    setleftMenuData([...leftMenuData]);
  };
  //单击左侧菜单
  const leftMenuClick = (_item: any, index: any) => {
    if (leftMenuClickTimeOut) {
      clearTimeout(leftMenuClickTimeOut);
    }
    leftMenuClickTimeOut = setTimeout(() => {
      // 更新点击状态
      for (let [i, v] of leftMenuData.entries() as any) {
        v["isEdit"] = false;
        if (i === index) {
          setgetMenus(v);
          v["isAct"] = true;
        } else {
          v["isAct"] = false;
        }
      }

      // setleftMenuData([...leftMenuData]);
      // 查询子菜单
      getChildMenu(_item);
    }, 200);
  };
  //双击左侧菜单
  const leftMenuDoubleClick = (_item: any, index: any) => {
    if (leftMenuClickTimeOut) {
      clearTimeout(leftMenuClickTimeOut);
    }
    leftMenuData[index]["isEdit"] = true;
    setleftMenuData([...leftMenuData]);
  };
  //左侧菜单输入框发生变化
  /*  const leftMenuIptChange = (e: any, index: any) => {
    leftMenuData[index]["iptVal"] = e.target.value;
    setleftMenuData([...leftMenuData]);
  };*/
  const leftMenuIptChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>, index: number) => {
      const newLeftMenuData = [...leftMenuData];
      newLeftMenuData[index]["iptVal"] = e.target.value;
      setleftMenuData(newLeftMenuData);
    },
    [leftMenuData]
  );

  //左侧菜单输入框keyup - 回车事件
  const handleEnterKey = (e: any, item: any, index: any) => {
    if (e.nativeEvent.keyCode === 13) {
      //e.nativeEvent获取原生的事件对像
      updateLeftMenu(item);
      leftMenuData[index]["isEdit"] = false;
      setleftMenuData([...leftMenuData]);
    }
  };
  //左侧菜单输入框 - 失去焦点事件
  /*  const handleBlur = (item: any, index: any) => {
    leftMenuData[index]["isEdit"] = false;
    setleftMenuData([...leftMenuData]);
    if (leftMenuData[index]["menuName"] !== leftMenuData[index]["iptVal"]) {
      updateLeftMenu(item);
    }
  };*/

  const handleBlur = (item: any, index: number) => {
    const newLeftMenuData = [...leftMenuData];
    newLeftMenuData[index]["isEdit"] = false;
    setleftMenuData(newLeftMenuData);

    if (newLeftMenuData[index]["menuName"] !== newLeftMenuData[index]["iptVal"]) {
      updateLeftMenu(item);
    }
  };

  // 更新、新增左侧树调接口
  const updateLeftMenu = (item: any) => {
    if (item.menuId) {
      // 更新接口
    } else if (!item.menuId && !item.iptVal) {
      leftMenuData.pop();
      setleftMenuData([...leftMenuData]);
    } else {
      console.log("切换数据---", item);
      saveMenu({ menuName: item.iptVal }).then((res: any) => {
        if (res.code == 200) {
          message.success("添加成功！");
          // setleftMenuData([...leftMenuData]);
        }
      });

      // setleftMenuData([...leftMenuData, item]);
      // 新增接口
    }
  };
  // 获取左侧菜单调接口
  const getLeftMenu = async (menuName: string) => {
    /*    // 假数据
    const fakeData: any = [
      { menuId: "all", menuName: "全部", menuOrder: null, infoCount: 0 },
      { menuId: "week", menuName: "最近7天", menuOrder: null, infoCount: 0 },
      { menuId: "today", menuName: "今天", menuOrder: null, infoCount: 0 },
      { menuId: "579319596561991045", menuName: "菜单1", menuOrder: 2, infoCount: 0 },
      { menuId: "579319809062208901", menuName: "菜单2", menuOrder: 3, infoCount: 0 },
      { menuId: "579319875135079813", menuName: "菜单3", menuOrder: 4, infoCount: 0 }
    ];
    for (const item of fakeData) {
      item["isEdit"] = false; // 是否编辑
      item["isAct"] = false; // 是否选中
      item["iptVal"] = item.menuName; // 编辑时input的值
    }
    if (fakeData.length) {
      fakeData[0]["isAct"] = true;
      getChildMenu(fakeData[0]);
    }
    setleftMenuData(fakeData);*/
    // return;
    // 真实交互
    const { code, data, msg }: { code: any; data: any; msg: string } = await getMyWorkMenu(menuName);
    if (code === 200) {
      for (const item of data) {
        item["isEdit"] = false; // 是否编辑
        item["isAct"] = false; // 是否选中
        item["iptVal"] = item.menuName; // 编辑时input的值
      }
      if (data.length) {
        data.slice(length - 3)[0]["isAct"] = true;
        // 查询子菜单
        getChildMenu(data.slice(length - 3)[0]);
      }
      if (getMenus?.menuId) {
        // 存选中值
        setgetMenus(getMenus);
      } else {
        setgetMenus(data.slice(length - 3)[0]);
      }

      // 将数组重新拼接
      setleftMenuData([...data.slice(length - 3), ...data.slice(0, length - 3)]);
    } else {
      message.error(msg);
    }
  };
  // 删除左侧树调接口
  const delLeftMenu = (item: any, index: any) => {
    /*   leftMenuData.splice(index, 1);
    setleftMenuData([...leftMenuData]);*/
    console.log(item.menuId, index);

    //     console.log("删除接口调用--", _item);
    // return;
    deleteMenu(item.menuId).then((res: any) => {
      if (res.code == 200) {
        message.success("删除成功!");
        getLeftMenu(getMenus.menuName);
      }
    });

    // 删除接口
  };
  // 右侧新增子菜单调接口
  const rightHandleEnterKey = (e: any) => {
    if (!rightChildAddValue) {
      return;
    }
    if (e.nativeEvent.keyCode === 13) {
      //e.nativeEvent获取原生的事件对像
      // console.log("获取输入值-----", e.target.value, getMenus.menuId);
      myworkInfoSaveMenu({ menuId: getMenus.menuId, content: e.target.value }).then((res: any) => {
        if (res.code == 200) {
          message.success("创建成功！");
          setrightChildAddValue("");
          getLeftMenu(getMenus.name);
        }
      });
      // 新增子菜单接口
    }
  };
  // 右侧删除子菜单调接口
  const delRightMenu = (_item: any, index: any) => {
    /*    rightChildArr.splice(index, 1);
    setrightChildArr([...rightChildArr]);*/
    // 删除列表接口
    console.log("删除列表接口", _item);
    deleteMyworkMenu(_item.id).then((res: any) => {
      if (res.code == 200) {
        message.success("删除成功！");
        // setleftMenuData([...leftMenuData]);
        getLeftMenu(getMenus.menuName);
        console.log("删除数据", res.data, index);
      }
    });
  };
  // 右侧子菜单点击完成调接口
  const rightMenuCheck = (_item: any, index: any) => {
    /*    rightChildArr[index]["isFinished"] = e.target.checked ? 1 : 0;
    setrightChildArr([...rightChildArr]);
    console.log("数据--", rightChildArr[index]);*/
    // 更新子菜单接口
    updateMyworkMenu({ id: rightChildArr[index].id, isFinished: 1 }).then((res: any) => {
      if (res.code == 200) {
        // myworkInfolistMenu("");
        console.log("切换数据--", res.data);
        getChildMenu(getMenus.menuId);
      }
    });
  };
  // 查询子菜单调接口
  const getChildMenu = (_item: any) => {
    // console.log("接口---", _item);
    // 查询子菜单接口
    myworkInfolistMenu({ menuId: _item.menuId, userId: "" }).then((res: any) => {
      if (res.code == 200) {
        setrightChildArr(res.data);
      }
    });
  };
  // 删除全部已完成调接口
  const delRightAllCheck = () => {
    // 删除已完成接口
    deleteFinishedMyworkMenu().then((res: any) => {
      if (res.code == 200) {
        message.success("删除成功！");
        setisShowModal(!isShowModal);
        setisShowDelAllCheck(false);
      }
    });
  };

  // 初始化渲染左侧菜单
  useEffect(() => {
    // 初次加载首页数据
    myworkInfolistMenu({ menuId: "", userId: "" }).then((res: any) => {
      // 数据分割
      // 2X2显示4条
      if (props.type === "list") {
        setgetList(
          res.data.filter((item: any, index: number) => {
            if (index <= 3) {
              return item;
            }
          })
        );
      }
    });
    if (isShowModal) {
      getLeftMenu("");
    }
  }, [isShowModal]);

  /*  useEffect(() => {
    // 仅在 isShowModal 改变时调用
    if (isShowModal) {
      getLeftMenu("");
    }
  }, [isShowModal]);*/

  return (
    <div>
      {props.type === "init" && (
        <div className="my_work_init">
          <h4>我的工作</h4>
          <span></span>
          <span></span>
        </div>
      )}
      {props.type === "list" && (
        <div className="my_work_list">
          <div className="my_work_list_tit">
            <div className="my_work_list_tit_icon">
              <div></div>
              <div></div>
              <img src={workIcon} alt="" />
            </div>
            <h4>我的工作</h4>
            <span
              onClick={() => {
                setisShowModal(!isShowModal);
              }}
            >
              更多
              <img src={moreWhite} alt="" />
            </span>
          </div>
          <div className="my_work_list_con">
            {getList?.map((page, index) => (
              <div key={index}>
                <Checkbox>{page.content}</Checkbox>
              </div>
            ))}
          </div>
        </div>
      )}
      {isShowModal ? (
        <div
          className="my_work_more_modal"
          onClick={() => {
            setisShowModal(!isShowModal);
          }}
        >
          <div
            className="my_work_more_modal_center"
            onClick={e => {
              e.stopPropagation();
            }}
          >
            <div className="my_work_more_modal_center_tit">
              <div className="my_work_more_modal_center_tit_icon">
                <div></div>
                <div></div>
                <img src={workIcon} alt="" />
              </div>
              <h4>我的工作</h4>
              <span>
                <img src={Work_2} alt="" onClick={() => modal_more_click()} />
                <img
                  src={Work_3}
                  alt=""
                  onClick={() => {
                    setisShowModal(!isShowModal);
                  }}
                />
                {isShowDelAllCheck && isShowModal ? (
                  <div>
                    <h4
                      onClick={() => {
                        delRightAllCheck();
                      }}
                    >
                      <img src={Work_11} alt="" />
                      删除已完成
                    </h4>
                    <span></span>
                  </div>
                ) : (
                  ""
                )}
              </span>
            </div>
            <div className="my_work_more_modal_content">
              <div>
                <div className="my_work_more_modal_content_left_top">
                  <input type="text" placeholder="请输入关键词" />
                  <div>
                    <img src={Work_1} alt="" />
                  </div>
                </div>
                <div className="my_work_more_modal_content_left_center">
                  {leftMenuData.map((item: any, index: any) => {
                    return (
                      <div
                        className={item.isAct ? "my_work_more_modal_content_left_center_active" : ""}
                        onClick={() => {
                          leftMenuClick(item, index);
                        }}
                        onDoubleClick={() => {
                          leftMenuDoubleClick(item, index);
                        }}
                        key={item.menuId ? item.menuId : index}
                      >
                        {(() => {
                          if (item.menuId === "all") {
                            return item.isAct ? <img src={Work_9_a} alt="" /> : <img src={Work_9} alt="" />;
                          } else if (item.menuId === "today") {
                            return item.isAct ? <img src={Work_8_a} alt="" /> : <img src={Work_8} alt="" />;
                          } else if (item.menuId === "week") {
                            return item.isAct ? <img src={Work_6_a} alt="" /> : <img src={Work_6} alt="" />;
                          } else if (item.isEdit) {
                            return <img src={Work_10} alt="" />;
                          } else {
                            return item.isAct ? <img src={Work_10} alt="" /> : <img src={Work_7} alt="" />;
                          }
                        })()}
                        {!item.isEdit && <h4>{item.menuName}</h4>}
                        {item.isEdit && (
                          <input
                            type="text"
                            placeholder="编辑名称"
                            value={item.iptVal}
                            onChange={e => {
                              leftMenuIptChange(e, index);
                            }}
                            onKeyUp={e => {
                              handleEnterKey(e, item, index);
                            }}
                            onBlur={() => {
                              handleBlur(item, index);
                            }}
                            onClick={e => {
                              e.stopPropagation();
                            }}
                          />
                        )}
                        {!item.isAct && <span>{item.infoCount}</span>}
                        {item.isAct && item?.menuId != "all" && item?.menuId != "week" && item?.menuId != "today" && (
                          <img
                            src={Work_11}
                            alt=""
                            className="my_work_more_modal_content_left_center_active_del"
                            onClick={() => {
                              delLeftMenu(item, index);
                            }}
                          />
                        )}
                        {item.isAct && (item?.menuId == "all" || item?.menuId == "week" || item?.menuId == "today") && (
                          <span>{item.infoCount}</span>
                        )}
                      </div>
                    );
                  })}
                </div>
                <div className="my_work_more_modal_content_left_bottom">
                  <h4
                    onClick={() => {
                      addLeftMenuClick();
                    }}
                  >
                    <img src={AddIcon} alt="" />
                    新建列表
                  </h4>
                </div>
              </div>
              <div>
                <div className="my_work_more_modal_content_right_top">
                  {rightChildArr.map((item: any, index: any) => {
                    return (
                      <div key={index}>
                        <Checkbox
                          checked={item.isFinished}
                          onChange={() => {
                            rightMenuCheck(item, index);
                          }}
                        >
                          {item.content}
                        </Checkbox>
                        {item.isFinished ? (
                          <img
                            src={Work_5}
                            alt=""
                            className="my_work_more_modal_content_right_top_del"
                            onClick={() => {
                              delRightMenu(item, index);
                            }}
                          />
                        ) : (
                          <img
                            src={Work_4}
                            alt=""
                            className="my_work_more_modal_content_right_top_del"
                            onClick={() => {
                              delRightMenu(item, index);
                            }}
                          />
                        )}
                      </div>
                    );
                  })}
                </div>

                {getMenus?.menuId != "all" && getMenus?.menuId != "week" && getMenus?.menuId != "today" && (
                  <div className="my_work_more_modal_content_right_bottom">
                    <input
                      type="text"
                      placeholder="今天有什么新工作要记录吗？"
                      value={rightChildAddValue}
                      onChange={e => {
                        setrightChildAddValue(e.target.value);
                      }}
                      onKeyUp={e => {
                        rightHandleEnterKey(e);
                      }}
                    />
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      ) : (
        ""
      )}
    </div>
  );
};
export default MyWork;
